package com.nine.common.tool;

/**
 * @Description: 雪花算法设计订单号
 * @ClassName: OrderController
 * @Author: luodeng
 * @Date: 2023/6/5 16:53
 * @Version: 1.0
 */


public class SnowflakeIdGenerator {
    private final long epoch = 1622779200000L; // 设置起始时间戳，单位为毫秒
    private final long workerIdBits = 5L; // 机器ID所占的位数
    private final long datacenterIdBits = 5L; // 数据中心ID所占的位数
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits); // 支持的最大机器ID，结果为31
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); // 支持的最大数据中心ID，结果为31
    private final long sequenceBits = 12L; // 序列号所占的位数
    private final long workerIdShift = sequenceBits; // 机器ID左移位数，即序列号占用的位数
    private final long datacenterIdShift = sequenceBits + workerIdBits; // 数据中心ID左移位数，即机器ID占用的位数
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // 时间戳左移位数，即数据中心ID占用的位数
    private final long sequenceMask = -1L ^ (-1L << sequenceBits); // 序列号掩码，用于限制序列号的范围
    private long lastTimestamp = -1L; // 上次生成ID的时间戳
    private long workerId; // 机器ID
    private long datacenterId; // 数据中心ID
    private long sequence = 0L; // 序列号

    public SnowflakeIdGenerator(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException("Worker ID超出范围");
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException("数据中心ID超出范围");
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    public synchronized long generateId() {
        long currentTimestamp = System.currentTimeMillis();

        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨，无法生成ID");
        }

        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                currentTimestamp = waitNextMillis(currentTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = currentTimestamp;

        long temp = ((currentTimestamp - epoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift)
                | sequence;
        String s = String.valueOf(temp);
        long uid = Long.parseLong(s.substring(s.length() - 12));

        return uid;
    }

    private long waitNextMillis(long currentTimestamp) {
        while (currentTimestamp <= lastTimestamp) {
            currentTimestamp = System.currentTimeMillis();
        }
        return currentTimestamp;
    }
}
